package com.gitee.fanx.retty;

import com.gitee.fanx.retty.web.ExceptionHandler;
import com.gitee.fanx.retty.web.ResponseHandler;
import com.gitee.fanx.retty.web.RouteMapping;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;

/**
 * Netty Handler 初始化
 *
 * @author fanhang
 */
final class NettyHandlerInitializer extends ChannelInitializer<SocketChannel> {

	private int maxContentLength;
	private RouteMapping routeMapping;
	private ResponseHandler responseHandler;
	private ExceptionHandler exceptionHandler;

	public NettyHandlerInitializer(int maxContentLength, RouteMapping routeMapping, ResponseHandler responseHandler, ExceptionHandler exceptionHandler) {
		this.maxContentLength = maxContentLength;
		this.routeMapping = routeMapping;
		this.responseHandler = responseHandler;
		this.exceptionHandler = exceptionHandler;
	}

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();
		pipeline.addLast(new HttpServerCodec());
		pipeline.addLast("aggregator", new HttpObjectAggregator(maxContentLength));
		// 将HttpRequestHandler放在业务线程池中执行，避免阻塞worker线程。
		pipeline.addLast("httpHandler", new HttpRequestHandler(routeMapping, responseHandler, exceptionHandler));
	}

}
